package avicit.bdp.dgs.metadata.rest;

import avicit.bdp.common.dto.ProcessInstanceDto;
import avicit.bdp.common.dto.request.dds.ProcessSchedulerDto;
import avicit.bdp.common.service.service.BdpCommonService;
import avicit.bdp.dgs.metadata.dto.MetadataCollectTaskDTO;
import avicit.bdp.dgs.metadata.dto.MetadataCollectTaskResult;
import avicit.bdp.dgs.metadata.service.MetadataCollectTaskResultService;
import avicit.bdp.dgs.metadata.service.MetadataCollectTaskService;
import avicit.platform6.core.rest.msg.QueryRespBean;
import avicit.platform6.core.rest.msg.ResponseMsg;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author mayi 元数据采集任务控制层
 */
@RestController
@Api(tags = "元数据采集任务")
@RequestMapping("/api/bdp/dgs/metadata/collect/task")
public class MetadataCollectTaskRest {

  @Resource private MetadataCollectTaskService metadataCollectTaskService;

  @Resource private BdpCommonService bdpCommonService;

  @Resource private MetadataCollectTaskResultService metadataCollectTaskResultService;

  @ApiOperation(value = "分页查询")
  @ApiImplicitParams({
    @ApiImplicitParam(
        value = "数据源类型",
        name = "datasourceType",
        dataType = "String",
        paramType = "query"),
    @ApiImplicitParam(value = "查询关键词", name = "keyWords", dataType = "String", paramType = "query"),
    @ApiImplicitParam(value = "当前页", name = "pageNo", dataType = "Int", paramType = "query"),
    @ApiImplicitParam(value = "每页大小", name = "pageSize", dataType = "Int", paramType = "query")
  })
  @GetMapping
  public ResponseMsg<QueryRespBean<MetadataCollectTaskDTO>> getPageList(
      @RequestParam(required = false) String datasourceType,
      @RequestParam(required = false) String keyWords,
      @RequestParam(defaultValue = "1") Integer pageNo,
      @RequestParam(defaultValue = "10") Integer pageSize)
      throws Exception {

    ResponseMsg<QueryRespBean<MetadataCollectTaskDTO>> responseMsg = new ResponseMsg<>();
    QueryRespBean<MetadataCollectTaskDTO> queryRespBean =
        metadataCollectTaskService.getPageList(datasourceType, keyWords, pageNo, pageSize);
    responseMsg.setResponseBody(queryRespBean);
    return responseMsg;
  }

  @ApiOperation(value = "新增")
  @PostMapping
  public ResponseMsg<String> save(@RequestBody MetadataCollectTaskDTO dto) {
    ResponseMsg<String> responseMsg = new ResponseMsg<>();
    metadataCollectTaskService.save(dto);
    responseMsg.setResponseBody(dto.getId());
    return responseMsg;
  }

  @ApiOperation(value = "编辑")
  @PutMapping
  public ResponseMsg<String> update(@RequestBody MetadataCollectTaskDTO dto) {
    ResponseMsg<String> responseMsg = new ResponseMsg<>();
    metadataCollectTaskService.update(dto);
    responseMsg.setResponseBody(dto.getId());
    return responseMsg;
  }

  @ApiOperation(value = "批量删除")
  @ApiParam(value = "逗号分隔的id串", name = "ids", required = true)
  @DeleteMapping
  public ResponseMsg<Boolean> batchDelete(@RequestBody String ids) {
    ResponseMsg<Boolean> responseMsg = new ResponseMsg<>();
    responseMsg.setResponseBody(metadataCollectTaskService.batchDelete(ids));
    return responseMsg;
  }

  @ApiOperation(value = "通过ID查询")
  @ApiParam(value = "id", name = "id", required = true)
  @GetMapping("/{id}")
  public ResponseMsg<MetadataCollectTaskDTO> queryById(@PathVariable String id) {
    ResponseMsg<MetadataCollectTaskDTO> responseMsg = new ResponseMsg<>();
    responseMsg.setResponseBody(metadataCollectTaskService.queryById(id));
    return responseMsg;
  }

  @ApiOperation(value = "启动任务")
  @ApiParam(value = "processDefinitionId", name = "流程ID", required = true)
  @GetMapping("/startTask")
  public ResponseMsg<Boolean> startTaskById(@RequestParam String processDefinitionId) {
    ResponseMsg<Boolean> responseMsg = new ResponseMsg<>();
    responseMsg.setResponseBody(
        metadataCollectTaskService.startTaskByProcessDefinitionId(processDefinitionId));
    return responseMsg;
  }

  @ApiOperation(value = "结束任务")
  @ApiParam(value = "processInstanceId", name = "流程实例ID", required = true)
  @GetMapping("/finishTaskByProcessInstanceId")
  public ResponseMsg<Boolean> finishTaskByProcessInstanceId(
      @RequestParam String processInstanceId) {
    ResponseMsg<Boolean> responseMsg = new ResponseMsg<>();
    responseMsg.setResponseBody(
        metadataCollectTaskService.executeByProcessInstanceId(processInstanceId, "STOP"));
    return responseMsg;
  }

  @ApiOperation(value = "根据流程ID查看定时任务")
  @ApiParam(value = "processDefinitionId", name = "流程ID", required = true)
  @GetMapping("/getScheduleByTaskId")
  public ResponseMsg<Map<String, Object>> getScheduleByTaskId(
      @RequestParam String processDefinitionId) {
    ResponseMsg<Map<String, Object>> responseMsg = new ResponseMsg<>();
    responseMsg.setResponseBody(
        metadataCollectTaskService.getScheduleByProcessDefinitionIdId(processDefinitionId));
    return responseMsg;
  }

  @ApiOperation(value = "保存/修改定时任务")
  @PostMapping("/saveSchedule")
  public ResponseMsg<Boolean> saveSchedule(@RequestBody ProcessSchedulerDto processSchedulerDto) {
    ResponseMsg<Boolean> responseMsg = new ResponseMsg<>();
    responseMsg.setResponseBody(
        metadataCollectTaskService.saveOrUpdateSchedule(processSchedulerDto));
    return responseMsg;
  }

  @ApiOperation(value = "启用/停用定时任务")
  @ApiImplicitParams({
    @ApiImplicitParam(
        value = "任务ID",
        name = "id",
        dataType = "String",
        paramType = "query",
        required = true),
    @ApiImplicitParam(
        value = "状态",
        name = "enable",
        dataType = "Int",
        paramType = "query",
        required = true)
  })
  @GetMapping("/releaseTask")
  public ResponseMsg<Boolean> releaseTask(@RequestParam String id, @RequestParam Integer enable) {

    ResponseMsg<Boolean> responseMsg = new ResponseMsg<>();
    responseMsg.setResponseBody(metadataCollectTaskService.releaseTask(id, enable));
    return responseMsg;
  }

  /**
   * query process instance list paging
   *
   * @param pageNo page number
   * @param pageSize page size
   * @param processDefinitionId process definition id
   * @param searchVal search value
   * @param executionStatus execution state
   * @param host host
   * @param startTime start time
   * @param endTime end time
   * @return process instance list
   */
  @ApiOperation(value = "查询监控列表")
  @ApiImplicitParams({
    @ApiImplicitParam(
        name = "processDefinitionId",
        value = "PROCESS_DEFINITION_ID",
        dataType = "String",
        required = true),
    @ApiImplicitParam(name = "searchVal", value = "SEARCH_VAL", type = "String"),
    @ApiImplicitParam(name = "executionStatus", value = "EXECUTION_STATUS", type = "Int"),
    @ApiImplicitParam(name = "host", value = "HOST", type = "String"),
    @ApiImplicitParam(name = "startDate", value = "START_DATE", type = "String"),
    @ApiImplicitParam(name = "endDate", value = "END_DATE", type = "String"),
    @ApiImplicitParam(name = "pageNo", value = "PAGE_NO", dataType = "Int", example = "1"),
    @ApiImplicitParam(name = "pageSize", value = "PAGE_SIZE", dataType = "Int", example = "10")
  })
  @GetMapping(value = "queryProcessInstanceListing")
  public ResponseMsg<QueryRespBean<ProcessInstanceDto>> queryProcessInstanceList(
      @RequestParam(value = "processDefinitionId") String processDefinitionId,
      @RequestParam(value = "searchVal", required = false) String searchVal,
      @RequestParam(value = "executionStatus", required = false) Integer executionStatus,
      @RequestParam(value = "host", required = false) String host,
      @RequestParam(value = "startDate", required = false) String startTime,
      @RequestParam(value = "endDate", required = false) String endTime,
      @RequestParam(defaultValue = "1") Integer pageNo,
      @RequestParam(defaultValue = "10") Integer pageSize) {

    ResponseMsg<QueryRespBean<ProcessInstanceDto>> responseMsg = new ResponseMsg<>();
    if (StringUtils.isNotEmpty(searchVal)) {
      searchVal = searchVal.replace("%", "////%");
    }
    QueryRespBean<ProcessInstanceDto> result =
        bdpCommonService.queryProcessInstanceList(
            processDefinitionId,
            startTime,
            endTime,
            searchVal,
            executionStatus,
            host,
            pageNo,
            pageSize);
    responseMsg.setResponseBody(result);
    return responseMsg;
  }

  @ApiOperation(value = "查询日志")
  @ApiImplicitParams({
    @ApiImplicitParam(
        value = "任务实例ID",
        name = "processInstanceId",
        dataType = "String",
        paramType = "query",
        required = true)
  })
  @GetMapping("/queryLog")
  public ResponseMsg<String> queryLog(@RequestParam String processInstanceId) {
    ResponseMsg<String> responseMsg = new ResponseMsg<>();
    responseMsg.setResponseBody(bdpCommonService.showLog(processInstanceId));
    return responseMsg;
  }

  @ApiOperation(value = "删除监控列表")
  @DeleteMapping("/deleteProcessInstance")
  public ResponseMsg<Boolean> deleteProcessInstance(@RequestParam String processInstanceId) {
    ResponseMsg<Boolean> responseMsg = new ResponseMsg<>();
    boolean deleteProcessInstance = bdpCommonService.deleteProcessInstanceById(processInstanceId);
    boolean deleteTaskInstance =
        bdpCommonService.deleteTaskInstanceByProcessInstanceId(processInstanceId);
    responseMsg.setResponseBody(deleteProcessInstance && deleteTaskInstance);
    return responseMsg;
  }

  @ApiOperation(value = "获取执行结果")
  @ApiImplicitParams({
    @ApiImplicitParam(
        name = "metadataCollectTaskId",
        value = "采集任务ID",
        dataType = "String",
        required = true),
    @ApiImplicitParam(
        name = "processInstanceId",
        value = "流程实例ID",
        type = "String",
        required = true)
  })
  @GetMapping("/result")
  public ResponseMsg<MetadataCollectTaskResult> result(
      @RequestParam String metadataCollectTaskId, @RequestParam String processInstanceId) {
    ResponseMsg<MetadataCollectTaskResult> responseMsg = new ResponseMsg<>();
    responseMsg.setResponseBody(
        metadataCollectTaskResultService.queryByCollectTaskIdAndTaskId(
            metadataCollectTaskId, processInstanceId));
    return responseMsg;
  }
}
